{% if site.leancloud.enable %}
  <script src="{{ site.baseurl }}/js/jquery-3.2.0.min.js"></script>
  <script src="{{ site.baseurl }}/js/av-min.js"></script>
  <script>AV.init("{{site.leancloud.app_id}}", "{{site.leancloud.app_key}}");</script>
  <script>
    //定义一个全局当前IP访问记录对象，用于更新访问记录、更新点赞记录
    var curIpVisitRecord = null;
    //定义一个全局当前文章对象，用于
    var curPost = null;
    //点赞更新是否完成，避免有人连续点击按钮，数据更新出错
    var bIsOperateEnd = true;

    //调用API获取IP
    function getVisitorIpAndJudge() {
      //note by PriestTomb 2018-07-08
      //freegeoip近期有变动，取ip改为用api.ipify.org，并设置"默认"ip:1.2.3.4
      //用json格式获取
      var ip = "1.2.3.4";
      var options = {
        type: 'GET',
        dataType: "json",
        //async: false, //jquery3中可以直接使用回调函数，不用再指定async
        url: "https://api.ipify.org/?format=json"
      };
      $.ajax(options)
      .done(function(data, textStatus, jqXHR) {
        if(textStatus == "success") {
          try {
            ip = data.ip;
          } catch (e) {
            ip = "1.2.3.4";
            if(window.console){
              console.log(e.message);
            }
          }
        } else {
          ip = "1.2.3.4";
        }
        saveOrUpdateIpRecord(ip);
      });
    }

    //判断访客是否已访问过该文章，及访问时间，符合条件则增加一次访问次数
    function saveOrUpdateIpRecord(ip) {
      var Visitor = AV.Object.extend("visitors_record");

      var $postInfo = $(".leancloud_visitors");
      var post_url = $postInfo.attr('id').trim();
      var query = new AV.Query(Visitor);

      query.equalTo("visitor_ip", ip);
      query.equalTo("post_url", post_url);
      query.find().then(function(results){
        if (results.length > 0) {
          if(window.console){
            console.log('该IP已访问过该文章');
          }

          curIpVisitRecord = results[0];
          updateIpRecord();
          refreshLikeBtn();
        } else {
          if(window.console){
            console.log('该IP第一次访问该文章，保存新的访问记录，并增加访问次数');
          }

          addPostVisitedTimes();
          addNewIpRecord(ip, post_url);
        }
      }, function(error){
        if(window.console){
          console.log('Error:' + error.code + " " + error.message);
        }
        addPostVisitedTimes();
      });
    }

    //新增访问次数
    function addPostVisitedTimes() {
      var AV_Posts = AV.Object.extend("Posts");

      // 页面（博客文章）中的信息：leancloud_visitors
      // id为page.url， data-flag-title为page.title
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(AV_Posts);

      // 只根据文章的url查询LeanCloud服务器中的数据
      query.equalTo("post_url", url);
      query.find().then(function(results){
        if (results.length > 0) {//说明LeanCloud中已经记录了这篇文章
          curPost = results[0];
          //curPost.fetchWhenSave(true);
          curPost.increment("visited_times",1);// 将点击次数加1
          curPost.save(null,{fetchWhenSave:true}).then(function(curPost){
            var $element = $(document.getElementById(url));
            var newTimes = curPost.get('visited_times');
            $element.find('.leancloud-visitors-count').text(newTimes);
          }, function(error){
            if(window.console){
              console.log('Failed to save Visitor num, with error message: ' + error.message);
            }
          });

          //加载点赞数
          loadLikeNums();
        } else {
          // 执行这里，说明LeanCloud中还没有记录此文章
          curPost = new AV_Posts();
          /* Set ACL */
          var acl = new AV.ACL();
          acl.setPublicReadAccess(true);
          acl.setPublicWriteAccess(true);
          curPost.setACL(acl);
          /* End Set ACL */
          curPost.set("post_title", title);// 把文章标题
          curPost.set("post_url", url); // 文章url
          curPost.set("visited_times", 1); // 初始点击次数：1次
          curPost.save().then(function(curPost){
            var $element = $(document.getElementById(url));
            var newTimes = curPost.get('visited_times');
            $element.find('.leancloud-visitors-count').text(newTimes);
          }, function(error){
            if(window.console){
              console.log('Failed to create');
            }
          });
        }
      }, function(error){
        if(window.console){
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    //仅根据url和title查出当前访问次数，不做+1操作
    function showPostVisitedTimes() {
      var AV_Posts = AV.Object.extend("Posts");

      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(AV_Posts);

      // 只根据文章的url查询LeanCloud服务器中的数据
      query.equalTo("post_url", url);
      query.find().then(function(results){
        if (results.length > 0) {//说明LeanCloud中已经记录了这篇文章
          curPost = results[0];
          var $element = $(document.getElementById(url));
          var newTimes = curPost.get('visited_times');
          $element.find('.leancloud-visitors-count').text(newTimes);

          loadLikeNums();
        } else {
          if(window.console){
            //新文章第一次打开时，会查不到记录，如果不是新文章第一次访问，那就是又有BUG了
            console.log('如果当前不是一篇新文章的第一次访问，那代表这是一种异常场景');
          }
        }
      }, function(error){
        if(window.console){
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    //更新IP访问记录(有规则限制)
    function updateIpRecord(){
      var lastTime = curIpVisitRecord.updatedAt;
      var curTime = new Date();

      var timePassed = curTime.getTime() - lastTime.getTime();

      if(timePassed > 1 * 60 * 1000) {
        if(window.console){
          console.log('距离该IP上一次访问该文章已超过了1分钟，更新访问记录，并增加访问次数');
        }

        addPostVisitedTimes();

        curIpVisitRecord.save().then(function(curIpVisitRecord){

        }, function(error){
          if(window.console){
            console.log('Failed to save visitor record, with error message: ' + error.message);
          }
        });
      } else {
        if(window.console){
          console.log('这是该IP 1分钟内重复访问该文章，不更新访问记录，不增加访问次数');
        }
      }
    }

    //添加新的IP访问记录
    function addNewIpRecord(ip, post_url){
      var Visitor = AV.Object.extend("visitors_record");

      curIpVisitRecord = new Visitor();
      /* Set ACL */
      var acl = new AV.ACL();
      acl.setPublicReadAccess(true);
      acl.setPublicWriteAccess(true);
      curIpVisitRecord.setACL(acl);
      curIpVisitRecord.set("visitor_ip", ip);
      curIpVisitRecord.set("post_url", post_url);
      curIpVisitRecord.save().then(function(curIpVisitRecord){ // 上传到LeanCloud服务器中

      }, function(error){
        if(window.console){
          console.log('Failed to create visitor record, with error message: ' + error.message);
        }
      });
    }

    //加载点赞数
    function loadLikeNums() {
      var likeTimes = curPost.get('like_times');
      $("#likeNum").text(likeTimes);
    }

    //刷新点赞按钮的状态
    function refreshLikeBtn() {
      var likeState = curIpVisitRecord.get('like_this_post');
      if(likeState == 1){
        $("#likeBtn").css("color", "red");
        $("#likeBtn").attr("onclick", "alert('点了赞还想取消？哼o(￣ヘ￣o＃)')");
        //mod by PriestTomb 2019-04-15 点了赞就憋想跑了
        //$("#likeBtn").attr("onclick", "likePost(-1)");
      } else {
        $("#likeBtn").css("color", "black");
        $("#likeBtn").attr("onclick", "likePost(1)");
      }
      loadLikeNums();
    }

    //点赞(取消点赞)了文章
    //type: 1-点赞
    function likePost(type) {
      if(curPost == null || curIpVisitRecord == null) {
        alert('别点那么快...请稍等...');
      }
      //避免狂点按钮，导致数据错乱的情况
      if(!bIsOperateEnd) {
        return
      }
      bIsOperateEnd = false;

      //更新 Posts 表的点赞数量
      var oldNum = parseInt(curPost.get('like_times'));
      var newNum = oldNum + parseInt(type);
      //curPost.fetchWhenSave(true);
      curPost.set('like_times', newNum);
      curPost.save(null, {fetchWhenSave:true}).then(function(curPost){
        //成功后再更新 visitors_record 表的 like_this_post 字段，避免两张表的数据不统一
        //curIpVisitRecord.fetchWhenSave(true);
        curIpVisitRecord.set("like_this_post", 1);
        curIpVisitRecord.save(null, {fetchWhenSave:true}).then(function(curIpVisitRecord){
          refreshLikeBtn();
          bIsOperateEnd = true;
        }, function(error){
          if(window.console){
            console.log('Failed to create visitor record, with error message: ' + error.message);
          }
          bIsOperateEnd = true;
        });
      }, function(error){
        if(window.console){
          console.log('Failed to create visitor record, with error message: ' + error.message);
        }
        bIsOperateEnd = true;
      });
    }

    //根据 json 格式的数据，刷新热门文章信息
    function refreshTopRead(articleListData) {
      if (!articleListData || articleListData == "") {
        $('.right').hide();
      } else {
        var ulObj = $('.top-read-list');
        var articleList = JSON.parse(articleListData);
        for(var i in articleList) {
          var articleObj = articleList[i]
          var liStr = "<li><a href='https://priesttomb.github.io"+articleObj.url+"'>"+articleObj.title+"</a><p class='read-num'>访问次数：<span>"+articleObj.num+"</span></p></li>";
          ulObj.append(liStr);
        }
      }
    }

    //从 LeanCloud 查询阅读次数最高的文章列表
    function getTopReadArticleList() {
      var articleListData = "";

      if (window.sessionStorage) { //浏览器支持 sessionStorage
        var storage = window.sessionStorage;
        articleListData = storage.getItem("articleListData");

        if (!articleListData) {
          //storage 中没数据时，要从 LeanCloud 查数据并存入
          articleListData = "";
          var AV_Posts = AV.Object.extend("Posts");
          var query = new AV.Query(AV_Posts);
          query.limit(5);
          query.addDescending('visited_times');
          query.find().then(function(results){
            if(results != null && results.length > 0) {
              for(var i = 0; i < results.length; i++) {
                var articleObj = results[i];
                var jsonStr = "{\"url\":\""+articleObj.get('post_url')+"\",\"title\":\""+articleObj.get('post_title')+"\",\"num\":\""+articleObj.get('visited_times')+"\"}";
                articleListData = articleListData + jsonStr;
                if (i < results.length - 1) {
                  articleListData = articleListData + ",";
                }
              }
              articleListData = "["+articleListData+"]";
              //保存到 sessionStorage
              storage.setItem("articleListData",articleListData);
              refreshTopRead(articleListData);
            }
          }, function(error){
            if(window.console){
              console.log('Failed to get post list, with error message: ' + error.message);
            }
            //异常时直接隐藏右边控件
            $('.right').hide();
          });
        } else {
          //有数据，直接刷新展示
          refreshTopRead(articleListData);
        }
      } else { //浏览器不支持，只能每次都查 LeanCloud，并直接刷新展示
        var AV_Posts = AV.Object.extend("Posts");
        var query = new AV.Query(AV_Posts);
        query.limit(5);
        query.addDescending('visited_times');
        query.find().then(function(results){
          if(results != null && results.length > 0) {
            var ulObj = $('.top-read-list')
            for(var i = 0; i < results.length; i++) {
              var articleObj = results[i];
              var liStr = "<li><a href='https://priesttomb.github.io"+articleObj.get('post_url')+"'>"+articleObj.get('post_title')+"</a><p class='read-num'>访问次数：<span>"+articleObj.get('visited_times')+"</span></p></li>";
              ulObj.append(liStr);
            }
          }
        }, function(error){
          if(window.console){
            console.log('Failed to get post list, with error message: ' + error.message);
          }
          //异常时直接隐藏右边控件
          $('.right').hide();
        });
      }
    }

    $(function() {
      if ($('.leancloud_visitors').length == 1) { //文章页面
        //先显示访问次数及赞数
        showPostVisitedTimes();

        //再获取ip，进行判断，对符合条件的访问增加访问次数
        getVisitorIpAndJudge();
      }

      //不限制页面，都获取并显示访问量前五的文章
      //getTopReadArticleList();
    });
  </script>
{% endif %}

<footer class="site-footer">
  <div class="footer-div">
    <div class="copyright">
      Copyright © 2019 Priest Tomb
    </div>
    <div>
      Powered by <a href="https://github.com/jekyll">Jekyll</a>
      &nbsp;|&nbsp;
      <a href="https://github.com/PriestTomb" style="color:black;">
        <i class="fa fa-github" aria-hidden="true"></i>
      </a>
      &nbsp;|&nbsp;
      <!-- 2017-12-14 加入站长统计 -->
      <span id='cnzz_stat_icon_1267535490'></span>
      <script src="https://s13.cnzz.com/z_stat.php?id=1267535490&show=pic" type='text/javascript'></script>
    </div>
  <div>
</footer>
